<?php
/**
 *@author sparkguo 
 *@date 2017-09-22 Ebay消息管理
 */
defined('BASEPATH') OR exit('No direct script access allowed');
ini_set('max_execution_time', '0');

class EbayMessage extends CI_Controller {
    
    public $dev_name = 'jrNUJmxg6aIsZbB';
    public $cert_name = 'CAjrkROW4t5zpyi';
    
	function __construct(){
		parent::__construct();
		$this->load->model('Function_m','fun');
		$this->load->model('EbayMessage_m','m');
		$this->pageSize =$this->config->item('pagenum');
        $this->CI =& get_instance();
        //$this->db148 = $this->CI->load->database('amazondata', TRUE);
    }
	//ebay账单列表
	public function getEbayBillList(){
		$where = "";
		$nowpage = $_REQUEST["pageid"];
		if ($nowpage == "")$nowpage = 1;
		$shopid = trim($this->input->get_post('shopid'));
		if($shopid)
		{
			$where .= " AND shopId = '{$shopid}' ";
			$this->tpl->assign("shopid",$shopid);
		}
		
		if($_COOKIE["department"] == 1 || $_COOKIE["department"] == 6)
		{
		}elseif($_COOKIE["department"] == 2){
			$where.= " AND types =1 ";
		}else{
			$where.= " AND createId = '".$_COOKIE['userid']."' ";
		}

		$startdate = trim($this->input->get_post('startdate'));
		if($startdate)
		{
			$where .= " AND startDate >= '{$startdate}' ";
			$this->tpl->assign("startdate",$startdate);
		}
		$enddate = $this->input->get_post('enddate');
		if($enddate)
		{
			$where .= " AND endDate <= '{$enddate}' ";
			$this->tpl->assign("enddate",$enddate);
		}
		$list = $this->fun->getalllist('db_ebay_bill',$where,$nowpage,$if_csv=0,$this->pageSize,$orderby);
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
		$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("total", $list["total"]);
		$this->tpl->assign("list",$list["list"]);
		$shoplist = $this->fun->getdatabaseslist('d_shop'," AND del_flag = 0 AND platfrom = 1 ","id,name");
		$this->tpl->assign("shoplist",$shoplist);
		$this ->tpl->display("EbayMessage/ebaybilllist.tpl");


	}
	public function addEbayBill(){
		if($this->input->post()){
			$result = $this->m->addEbayBill();
			if($result){
				header("Location:/EbayMessage/getEbayBillList");exit;
			}

		}else{
			$id = trim($this->input->get("id"));
			if($id){
				$detail = $this->fun->getdatabasesdetail("db_ebay_bill"," AND id = '{$id}' ");
				$this->tpl->assign("detail",$detail);
			}
			$shoplist = $this->fun->getdatabaseslist('d_shop'," AND del_flag = 0 AND platfrom = 1 ","id,name");
			$this->tpl->assign("shoplist",$shoplist);
			$this->tpl->display("EbayMessage/addebaybill.tpl");
		}
	}
    
    function ajaxbutton(){
		$op = trim($this->input->get_post('op'));	
        //国家销售额报表
        if($op =='messageDetail'){
            $this->messageDetail();
		}
        //返回店铺列表
        if($op =='messageText'){
            $this->messageText();
		}
        if($op =='replyMessage'){
            $this->replyMessage();
		}
        if($op =='setMsgFlag'){
            $this->setMsgFlag();
		}
        //更新线上回复
        if($op =='updateOnlineReply'){
            $this->updateOnlineReply();
		}
        if($op == "delEbayBill"){
		    $id = trim($this->input->post("id"));
		    $detail = $this->fun->getdatabasesdetail("db_ebay_bill"," AND id = '".$id."'");
		    if($detail){
			     if($detail['excelUrl']){
				     $excel_url = dirname(__FILE__)."/../..".$detail['excelUrl'];
				     @unlink($excel_url);
			     }
			    $this->db->delete("db_ebay_bill"," id = '".$id."'");
			    echo 200;exit;

		    }else{
			    echo 201;exit;
		    }

	    }
	} 
    
    //消息列表
    public function index(){
       
		$nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        //---处理where查询条件
        $where = "";
        $search_data=$this->input->get();
        $starttime=trim($search_data['starttime']);
        $endtime=trim($search_data['endtime']);
        $msg_flag=array(1=>"Case已回复",3=>"违规警告",2=>"重复邮件",4=>"无需回复");
        if(!empty($search_data['shop_id'])){
            $where.=" && shop_id=".$search_data['shop_id'];    
        }
        if(!empty($search_data['messagetype'])){
            $where.=" && MessageType='".$search_data['messagetype']."'";    
        }
        if(!empty($search_data['messageid'])){
            $where.=" && db_ebaymessage.MessageID=".$search_data['messageid'];    
        }
        if(!empty($search_data['customer'])){
            $where.=" && db_ebaymessage.Sender like '%".$search_data['customer']."%'";    
        }
        if(!empty($search_data['message_state'])){
            $message_state=$search_data['message_state']==2?'0':$search_data['message_state'];
            $where.=" && Replied=".$message_state;    
        }
        if(!empty($search_data['starttime'])){ 
            $where.=$endtime!=''?"and ReceiveDate between '".$starttime."' and '".$endtime."'":" and ReceiveDate>='".$starttime."'"; 
        }     
                
        $tpl_data=array("shop_id"=>$search_data['shop_id'],'messageid'=>$search_data['messageid'],
        'starttime'=>$starttime,'endtime'=>$endtime,'message_state'=>$search_data['message_state'],'customer'=>$search_data['customer']);
		$list = $this->fun->getalllist("db_ebaymessage left join db_ebaymessage_reply on db_ebaymessage_reply.MessageID=db_ebaymessage.MessageID", $where, $nowpage, $if_csv, $this->pageSize,
        " order by ReceiveDate desc","*,db_ebaymessage.MessageID as MessageID,db_ebaymessage.update_online as update_online");
        $shopdata=$this->fun->getdatabaseslist('d_shop', " AND del_flag= 0 and platfromname='ebay'", 'id,name,updateoper', ' order by name asc');
        $newshopdata=array();
        foreach($shopdata as $key=>$shopinfo){
            $newshopdata[$shopinfo['id']]=$shopinfo;       
        }
        $customer_arr=array();
        foreach( $list["list"] as $key=>$messageinfo){
            $itemid=$messageinfo['Sender'];
            if(!empty($itemid)){
                //$orderinfo=$this->fun->getdatabasesdetail("db_order_list","AND ebay_orderID like '$itemid%'");
                $customer_arr[]=$itemid;
                //$list["list"][$key]['order_sn']= $orderinfo['order_sn'];   
            }
            $list["list"][$key]['shop_name']=$newshopdata[$messageinfo['shop_id']]['name'];
            $list["list"][$key]['shop_owner']= $newshopdata[$messageinfo['shop_id']]['updateoper'];         
        }
        if(count($customer_arr)>0){
            $customer_arr_str = implode("','", $customer_arr);
            $reslist = $this->db->get_where("db_order_list", "  customerid in('" . $customer_arr_str . "')")->result_array();
            //echo $this->db->last_query();
            $new_orders=array();
            foreach($reslist as $key=>$val){
                //$itemid=explode('-',$val['ebay_orderID']);
                $new_orders[$val['customerid']]=$val;    
            }
            //dump($new_orders);
		}
        foreach( $list["list"] as $key=>$messageinfo){
            $itemid=$messageinfo['Sender'];
            $list["list"][$key]['order_sn']= $new_orders[$itemid]['order_sn']; 
        }
        
        $tpl_data['msg_flag']=$msg_flag;
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("d_shop", $shopdata);
        $this->tpl->assign($tpl_data);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("orderlist", $list["list"]);
        
        
          //echo $this->db->last_query(); 
        $result_classid = $this->fun->getClassId();//获取部门信息
        $department=array(); //存部门信息
        foreach($result_classid as $key=>$dept){
            $department[$dept['id']]=$dept['name'];        
        }
        $this->tpl->assign('ownerlist',$ownerlist);
        $this->tpl->assign("classid", $result_classid);
        $this->tpl->assign("department", $department);
        $this->tpl->display("EbayMessage/index.tpl");
    }
    
    public function setMsgFlag(){
        $msgflag=$this->input->post("msg_flag");
        $msgid=$this->input->post("msgid");
        $savedata=array('msg_flag'=>$msgflag);
        $this->db->update('db_ebaymessage', $savedata, 'id='.$msgid); 
        $ret_json=array("state"=>'success','msg'=>'ok');
        echo json_encode($ret_json); 
    }
    //导入平台消息
    public function importMsg(){
        //本地的本地获取消息
        
        $deleteTimeWeek=date("Y-m-d H:i:s",strtotime("-10 day"));
        //dump($deleteTimeWeek);
        //$this->db->query("DELETE db_ebaymessage_detail FROM db_ebaymessage_detail,
        //db_ebaymessage WHERE db_ebaymessage_detail.MessageID=db_ebaymessage.MessageID and db_ebaymessage.ImportTime<='$deleteTimeWeek'");
        $Messageinfo = $this->fun->getdatabasesdetail("db_ebaymessage A left join db_ebaymessage_detail B on A.MessageID=B.MessageID","and ImportTime<='$deleteTimeWeek'",'*',"order by ImportTime desc");
        if($Messageinfo['detail_id']>0){
            $this->db->query("DELETE FROM db_ebaymessage_detail WHERE detail_id<$Messageinfo[detail_id]");   
        }
        $deleteTimeWeek=date("Y-m-d H:i:s",strtotime("-30 day"));
        $this->db->query("DELETE FROM db_ebaymessage WHERE ImportTime<'$deleteTimeWeek' and  Replied<1");
        $shop_list = $this->db->get_where("d_shop","platfrom=1 and amazonkey<>'' and agent_visit=0")->result_array();//获取店铺token  and name='just4funforever'
        
         $err_messageList=$this->db->query("select * from db_ebaymessage A left join db_ebaymessage_detail B on A.MessageID=B.MessageID where detail_id is null ")->result_array();
        $err_msgid=array();
        foreach($err_messageList as $index=>$err_msg){
            $err_msgid[]=$err_msg['id'];   
            
        }
        if(count($err_msgid)>0){
            $err_msgid=implode(',',$err_msgid);
            $this->db->delete("db_ebaymessage","id in(".$err_msgid.")");
        }
        foreach($shop_list as $key=>$shopinfo){
            echo "down shop:".$shopinfo['name']."'s messages<br />";
            $this->m->getShopMessage($shopinfo['id']);       
        }
        /*
        $messageList=$this->db148->query("select * from db_ebaymessage A left join db_ebaymessage_detail B on A.MessageID=B.MessageID where A.import_flag=0")->result_array();
        foreach($messageList as $key=>$msginfo){
            $msginfo['ItemID']=$msginfo['ItemID']==null?'':$msginfo['ItemID'];
            $into=array("Sender"=>$msginfo['Sender'],"SendToName"=>$msginfo['SendToName'],"Subject"=>$msginfo['Subject'],
            "MessageID"=>$msginfo['MessageID'],'ExternalMessageID'=>$msginfo['ExternalMessageID'],
            "Read"=>$msginfo['Read'],"Replied"=>$msginfo['Replied'],"ReceiveDate"=>$msginfo['ReceiveDate'],'shop_id'=>$msginfo['shop_id'],
            "MessageType"=>$msginfo['MessageType'],'ItemID'=>$msginfo['ItemID'],"SendingUserID"=>$msginfo['SendingUserID']);
            $into['ImportTime']=date("Y-m-d H:i:s");
            $MessageID=$msginfo['MessageID']; 
            if($MessageID==null or $MessageID==''){
                echo 'have no messages,';
                //$this->db148->delete("db_ebaymessage","id=".$msginfo['id']);
                //continue;    
            }
            $rs=$this->fun->getdatabasesdetail("db_ebaymessage","AND MessageID ={$MessageID}"); 
            
            if($rs==null){
                $insertid=$this->db->insert("db_ebaymessage",$into); 
                 echo "down 148message messageid:{$into['MessageID']} success<br />";
                $msg_detail_data=array("MessageID"=>$msginfo['MessageID'],"Text"=>$msginfo['Text']);
                //echo $this->db->last_query();
                $insertid=$this->db->insert("db_ebaymessage_detail",$msg_detail_data);
                echo "down 148messageDetail messageid:{$msginfo['MessageID']} success<br />";
            }
            $this->db148->update("db_ebaymessage",array("import_flag"=>'1'),"id=".$msginfo['id']);
            // echo $this->db->last_query();
        }
        $replyList=$this->db148->query("select * from db_ebaymessage_reply where import_flag=0 && update_online>0")->result_array();
        foreach($replyList as $replyinfo){
            $this->db->update("db_ebaymessage",array("update_online"=>$replyinfo['update_online']),"MessageID=".$replyinfo['MessageID']);
            $this->db->update("db_ebaymessage_reply",array("update_online"=>$replyinfo['update_online'],"ret_msg"=>$replyinfo['ret_msg']),"MessageID=".$replyinfo['MessageID']);   
            $this->db148->update("db_ebaymessage_reply",array("import_flag"=>'1'),"reply_id=".$replyinfo['reply_id']); 
            echo "revice messagereply messageid:{$replyinfo['MessageID']} success<br />";    
        }
        */
        echo '同步线上消息完成';
    }
    
    //消息详细
    public function messageDetail(){
        $id=$this->input->get("id");
        $message = $this->fun->getdatabasesdetail("db_ebaymessage A left join db_ebaymessage_detail B on A.MessageID=B.MessageID","AND A.id ={$id}","*,A.MessageID as MessageID"); 
        $subtitinfo = $this->fun->getdatabasesdetail("db_ebaymessage","AND id ={$id}");
        $replyinfo=$this->fun->getalllist("db_ebaymessage_reply","AND MessageID ={$subtitinfo[MessageID]}", null,0,200," order by reply_id asc");
         $senderinfo=$message['Sender'];
         if($senderinfo!='eBay'){
            $rs=$this->fun->getdatabasesdetail("db_order_list","AND customerid = '$senderinfo'"); 
            if($message['detail_id']==''){
                //$this->m->getShopMessage($message['shop_id'],$message['MessageID']);    
            }
            $result_data = $this->fun->getalllist("db_order_list","AND customerid = '$senderinfo'", 
            1, 0, $this->pageSize," order by dates desc","*");
            $datalist=$result_data['list'];
            if(count($datalist)>0){
                $orderlist=array();
                foreach($datalist as $key=>$rs){
                    switch ($rs["order_status"]) {
                        case 1;
                            $rs["statustext"] = '新订单';
                            break;
                        case 2:
                            $rs["statustext"] = '已支付';
                            break;
                        case 3:
                            $rs["statustext"] = '配货中';
                            break;
                        case 4:
                            $rs["statustext"] = '已发货';
                            break;
                        case 5:
                            $rs["statustext"] = '已完成';
                            break;
                        case 6:
                            $rs["statustext"] = '已作废';
                            break;
                        case 7:
                            $rs["statustext"] = '待审查';
                            break;
                    }
                    $rs["numday"] = intval((time() - strtotime($rs["ordertime"])) / 86400); //延迟天数
                    $rs["goods_total"] = $rs["goods_amount"] + $rs["shipping_fee"]; //订单合计金额 = 商品金额+运费-平台-支付-商品成本
        
                    $shop = $this->fun->getdatabasesdetail("d_shop", " AND name='" . $rs["shopname"] . "'");    //负责人
                    $rs["responsible"] = $shop["updateoper"];
                    $rs["platfromname"] = $shop["platfromname"];
        			$rs["add_time"] = date("Y-m-d H:i:s",$rs["add_time"]);
                    $orderlist[]=$rs;
                }
                $this->tpl->assign("orderlist",$orderlist);
            }
            
         }
        $message['MessageID']=$subtitinfo['MessageID'];
       // dump($subtitinfo['MessageID']);
       // dump($message);
       
       foreach($replyinfo['list'] as $skey=>$rep){
            $replyinfo['list'][$skey]['replyinfo']=$this->htmlencode($rep['replyinfo']); 
       }
        $this->tpl->assign("replylist", $replyinfo['list']);
        $this->tpl->assign("detail", $message);
        $this->tpl->display("EbayMessage/messageDetail.tpl");
    }
    function htmlencode($str){
        $str = str_replace(chr(32), '&nbsp;', $str);
        return nl2br($str);
    }
    
    public function messageText(){
         $MessageID=$this->input->get("MessageID");
        $message = $this->fun->getdatabasesdetail("db_ebaymessage_detail","AND MessageID ={$MessageID}"); 
        $this->tpl->assign("detail", $message);
        $data=$this->tpl->fetch('EbayMessage/messageText.tpl');
        echo $data;    
    }
    
    //回复
    public function replyMessage(){
        $messageid=$this->input->post("MessageID"); 
        $body=$this->input->post("replyinfo"); 
        $witer=$_COOKIE['username'];
        $witerid=$_COOKIE["useraccount"];
        $shopid=$this->input->post("shop_id");
        $into=array("MessageID"=>$messageid, "replyinfo"=>$body, "witer"=>$witer,"witerid"=>$witerid, "create_time"=>date("Y-m-d H:i:s"));
        $shopinfo=$this->fun->getdatabasesdetail("d_shop","AND id =$shopid");
        if($shopinfo['agent_visit']==1){//远程访问
            $insert_state=$this->db148->insert("db_ebaymessage_reply",$into); 
            $insert_state=$this->db->insert("db_ebaymessage_reply",$into);
            $savedata=array('update_online'=>0,'Replied'=>1);
            $this->db->update('db_ebaymessage', $savedata, 'MessageID='.$messageid);  
            $into['insert_state']=$insert_state; 
            $upOnlineRet=array("state"=>'not_full_success','msg'=>'ok');  
            if($shopinfo["agent_site"]){
                 //$reply_ret=$this->sendHttpRequest(trim($shopinfo["agent_site"],'/')."/ebay.php?action=actionReply",'aaaa=aaaa'); 
                //dump($reply_ret);   
                $replyurl=trim($shopinfo["agent_site"],'/')."/ebay.php?action=actionReply";
                $upOnlineRet['replyurl']=$replyurl;
            }
             
        }else{
            $insert_state=$this->db->insert("db_ebaymessage_reply",$into);
            $into['insert_state']=$insert_state;
            $insertid=$this->db->insert_id();
            $into['insertid']=$insertid;  
            $messageinfo=$this->fun->getdatabasesdetail("db_ebaymessage","AND MessageID ={$messageid}"); 
            $into['msg_info']=$messageinfo;
            $upOnlineRet=$this->m->updateOnlineReply($into); 
        }

        $into['agent_visit']=$shopinfo['agent_visit'];
        $into['up_online_ret']=$upOnlineRet;
        $returndata=json_encode($into);
        echo $returndata;
    }
    
    /**
     * Call DHL Service
     * @param Request $request Request to send
     * 
     * @return string DHL XML response string
     */
    public function sendHttpRequest($url,$request){
        if (!$ch = curl_init()){
            throw new \Exception('could not initialize curl');
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_PORT , 443);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$request);
        $result = curl_exec($ch);
        
        if (curl_error($ch))
        {
            return false;
        }
        else
        {
            curl_close($ch);
        }

        return $result;
    }
    
}
